package com.masterclient.app.businessmodule.vipmodule.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PagerSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.eoner.baselib.fragment.FCBaseFragment;
import com.eoner.baselib.widget.navgation.FCNavigationBar;
import com.eoner.baselibrary.utils.GlideUtil;
import com.eoner.baselibrary.utils.Utils;
import com.eoner.middlelib.eventbus.event.LoginSuccessEvent;
import com.eoner.uikit.header.MyRefreshHead;
import com.masterclient.app.R;
import com.masterclient.app.businessmodule.vipmodule.activity.PromotionProfitActivity;
import com.masterclient.app.businessmodule.vipmodule.adapter.MemberAdapter;
import com.masterclient.app.businessmodule.vipmodule.bean.AdArr;
import com.masterclient.app.businessmodule.vipmodule.bean.Level;
import com.masterclient.app.businessmodule.vipmodule.bean.Member;
import com.masterclient.app.businessmodule.vipmodule.persenter.VipCenterContract;
import com.masterclient.app.businessmodule.vipmodule.persenter.VipCenterPresenter;
import com.masterclient.app.businessmodule.vipmodule.view.AgentMemberView;
import com.masterclient.app.modules.bridge.BridgeActivity;
import com.masterclient.app.widget.CircleImage;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.eoner.uikit.header.MyRefreshHead.LOTTIE;

/**
 * 会员中心
 */
public class VipCenterFragment extends FCBaseFragment<VipCenterPresenter> implements VipCenterContract.View {
    public static final int ADD_ADDRESS_CODE = 112;
    public static String TAG = "VipCenterFragment";
    @BindView(R.id.head_iv)
    CircleImage headIv;
    @BindView(R.id.name_tv)
    TextView nameTv;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.profit_tv)
    TextView profitTv;
    @BindView(R.id.profit_v)
    FrameLayout profitV;
    @BindView(R.id.peoples_tv)
    TextView peoplesTv;
    @BindView(R.id.power_iv)
    ImageView powerIv;
    @BindView(R.id.ad1_iv)
    ImageView ad1Iv;
    @BindView(R.id.ad2_iv)
    ImageView ad2Iv;
    @BindView(R.id.agmentView)
    AgentMemberView agmentView;
    @BindView(R.id.smartRefresh)
    SmartRefreshLayout smartRefresh;

    private PagerSnapHelper mPagerSnapHelper;
    private LinearLayoutManager linearLayoutManager;
    private MemberAdapter adapter;
    private MyRefreshHead myRefreshHead;
    private List<AdArr> adArr;
    public String member_h5_url;// 等级说明
    public String break_h5_url;// 推广会员
    public String exp_h5_url;// 成长值
    public String be_dealer_url;// 成为经销商
    public String shop_keeper_url;// 开通店主
    private Member member;
    @Override
    protected int requireGetLayoutId() {
        return R.layout.fragment_vip;
    }

    @Override
    protected void requireSetCustomNavigationBar(FCNavigationBar navigationBar) {
        navigationBar.setTitle("会员中心")
                .setTitleColor(R.color.white)
                .showStatusBar()
                .setLeftImageBtnHidden(true)
                .setLineHidden(true)
                .setBgColor(ContextCompat.getColor(getContext(), R.color.color_212121));
    }

    @Override
    protected void requireInitUIAndData(Bundle savedInstanceState) {
        initSmartRefresh();
        initRecycler();
        openArea();
        mPresenter.getVipData();
        // 设置字体样式
        Utils.setDin(profitTv, getContext());
        Utils.setDin(peoplesTv, getContext());
    }

    @Override
    public void onResume() {
        super.onResume();
//        if (((MainActivity)getActivity()).curPosition == 1) {
//
//        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if(null != member){// 选中当前等级
                List<Level> levels = member.getLevel_list();
                selectCard(levels);
            }

           // openArea();
        }
    }

    protected boolean useEventBus() {
        return true;
    }

    /**
     * 登录成功刷新
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void loginSuccessEvent(LoginSuccessEvent event) {
        mPresenter.getVipData();
    }

    /**
     * 初始化下来刷新控件
     */
    private void initSmartRefresh() {
        myRefreshHead = new MyRefreshHead(getContext(), 1, LOTTIE);
        myRefreshHead.changeBackColor(Color.parseColor("#212121"));
        myRefreshHead.changeTextColor(Color.parseColor("#FFFFFF"));
        smartRefresh.setRefreshHeader(myRefreshHead);
        smartRefresh.setOnRefreshListener(refreshLayout -> mPresenter.getVipData());
    }

    /**
     * 设置 recyclerview
     */
    private void initRecycler() {

        adapter = new MemberAdapter(getContext());
        recyclerView.setNestedScrollingEnabled(false);
        linearLayoutManager = new LinearLayoutManager(getContext()
                , LinearLayoutManager.HORIZONTAL, false);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(linearLayoutManager);
        mPagerSnapHelper = new PagerSnapHelper();
        mPagerSnapHelper.attachToRecyclerView(recyclerView);
        addOnScrollListener();
    }

    /**
     * 监听recyclerview 滚动事件
     * 不同会员显示不同界面
     */
    private void addOnScrollListener() {
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    //暂停
                    View viewIdle = mPagerSnapHelper.findSnapView(linearLayoutManager);
                    if (viewIdle != null) {
                        int position = linearLayoutManager.getPosition(viewIdle);
                        String privilege_img = adapter.getLevel(position).getPrivilege_img();
                        setPrivilegeImg(privilege_img);
//                        if (level <= 2) {// 注册 vip会员
//                            //  profitV.setVisibility(View.GONE);
//                            agmentView.setVisibility(View.GONE);
//                        } else if (level == 3) {//银卡会员
//                            // profitV.setVisibility(View.VISIBLE);
//                            agmentView.setVisibility(View.GONE);
//                        } else {// 金卡及以上会员
//                            //  profitV.setVisibility(View.VISIBLE);
//                            agmentView.setVisibility(View.VISIBLE);
//                        }
                    }
                }
            }
        });
    }

    @OnClick({R.id.level_tv, R.id.ad1_iv, R.id.ad2_iv, R.id.member_v, R.id.profit_v})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.level_tv:// 等级说明
                startWebViewActivity("等级说明", member_h5_url);
                break;
            case R.id.ad1_iv:
                AdArr adArr0 = adArr.get(0);
                startWebViewActivity("dimissTitle", be_dealer_url);
                break;
            case R.id.ad2_iv:
                AdArr adArr1 = adArr.get(1);
                startWebViewActivity("dimissTitle", shop_keeper_url);
                break;
            case R.id.member_v:// 推广会员
                startWebViewActivity("推广会员", break_h5_url);
                break;
            case R.id.profit_v:// 推广收益
                startActivity(new Intent(getContext(), PromotionProfitActivity.class));
                break;
        }
    }

    /**
     * 跳转到添加收货地址
     */
    private void openArea() {
        // 判断是否有收货地址先注释掉
//        if (!UserDataManager.getInstance().getCheckRefundAddress()) {
//            if (!UserDataManager.getInstance().isShowAfterAddress) {
//                UserDataManager.getInstance().isShowAfterAddress = true;
//                getActivity().startActivityForResult(new Intent(getContext(), AddAddressActivity.class), ADD_ADDRESS_CODE);
//                getActivity().overridePendingTransition(R.anim.slide_in_from_bottom, 0);
//            }
//        }
    }

    @Override
    public void vipData(Member member) {
        finishRefresh();
        if (member != null) {
            member_h5_url = member.getMember_h5_url();
            exp_h5_url = member.getExp_h5_url();
            break_h5_url = member.getBreak_h5_url();
            boolean check_profit_show = member.isCheck_profit_show();
            if (check_profit_show)
                profitV.setVisibility(View.VISIBLE);
            else profitV.setVisibility(View.GONE);
            int level = member.getLevel();
            if (level > 3) {//金卡及以上会员
                agmentView.setVisibility(View.VISIBLE);
            } else {
                agmentView.setVisibility(View.GONE);
            }
            be_dealer_url = member.getBe_dealer_url();
            shop_keeper_url = member.getShop_keeper_url();
            // 设置会员等级卡片
            List<Level> levels = member.getLevel_list();
            adapter.setMemberList(levels, level, this);
            selectCard(levels);
            // 设置等级特权图片
            setPrivilegeImg(member.getPrivilege_img());
            String nickName = member.getNick_name();
            nameTv.setText(nickName);
            String avatar = member.getAvatar();
            if (null != avatar)
                GlideUtil.displayImage(getContext(), avatar, headIv, R.mipmap.user_head_default_icon);

            adArr = member.getAd_arr();
            showAd(adArr);
            // 设置金卡及以上信息
            agmentView.setDealerShop(member.getDealer_shop(), member.getDealer_profit());
            // 推广收益
            String totalProfits = member.getTotal_profits();
            profitTv.setText(totalProfits);
            String all_vip_num = member.getAll_vip_num();
            // 推广会员
            peoplesTv.setText(all_vip_num);
            this.member = member;
        }

    }

    /**
     * 设置等级特权图片
     *
     * @param privilegeImg
     */
    private void setPrivilegeImg(String privilegeImg) {
        if (null != privilegeImg) {
            powerIv.setVisibility(View.VISIBLE);
            Glide.with(getContext()).load(privilegeImg).into(powerIv);
        } else powerIv.setVisibility(View.GONE);
    }

    /**
     * 设置选中那个卡片
     *
     * @param levels
     */
    private void selectCard(List<Level> levels) {

        for (int i = 0; i < levels.size(); i++) {
            Level level = levels.get(i);
            if (level.isCheck()) {
                recyclerView.smoothScrollToPosition(i);
                return;
            }
        }
    }

    /**
     * 显示隐藏广告图
     *
     * @param adArr
     */
    private void showAd(List<AdArr> adArr) {
        if (adArr != null && adArr.size() > 0) {
            String adArr1 = adArr.get(0).getIcon();
            if (!TextUtils.isEmpty(adArr1)) {
                ad1Iv.setVisibility(View.VISIBLE);
                GlideUtil.displayImage(getContext(), adArr1, ad1Iv,R.drawable.product_default);
            }
            if (adArr.size() > 1) {
                String adArr2 = adArr.get(1).getIcon();
                if (!TextUtils.isEmpty(adArr2)) {
                    ad2Iv.setVisibility(View.VISIBLE);
                    GlideUtil.displayImage(getContext(), adArr2, ad2Iv,R.drawable.product_default);
                }
            }
        } else {
            ad1Iv.setVisibility(View.GONE);
            ad2Iv.setVisibility(View.GONE);
        }
    }

    /**
     * 隐藏下拉刷新
     */
    public void finishRefresh() {
        if (smartRefresh != null) {
            smartRefresh.finishRefresh();
        }
    }

    /**
     * 跳转到H5
     *
     * @param title
     * @param url
     */
    private void startWebViewActivity(String title, String url) {
        if(TextUtils.isEmpty(url))
            return;
        startActivitryWithBundle(BridgeActivity.class, new String[][]{{"url", url}, {"title", title}});
    }

}
